//
//  TasteTypeViewController.m
//  XDCommonApp
//
//  Created by maboyi on 14-6-23.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "TasteTypeViewController.h"
#import "TypeListViewController.h"
#import "NSString+MD5.h"
#import "LoginViewController.h"
#import "UIImageView+WebCache.h"
#import "ThreePriceViewController.h"
#import "GoodsDetailViewController.h"
@interface TasteTypeViewController ()

@end

@implementation TasteTypeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    [headIV openTimerTask];
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    dataArray = [[NSMutableArray alloc] init];
    btnArray = [[NSMutableArray alloc] init];
    
    self.titleLabel.text = @"支付";
	
    UIScrollView * backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT)];
    backScrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, 512);
    [self.contentView addSubview:backScrollView];
    
//    headerScrollView = [[XYScrollView alloc] initPageScrollView:CGRectMake(0, 0, UI_SCREEN_WIDTH, 285) pageControllerFrame:CGRectMake(256, 267, 50, 15) backgroudImage:nil pageNumber:3];
//    headerScrollView.delegate = self;
//    headerScrollView.backgroundColor = [UIColor orangeColor];
//    [backScrollView addSubview:headerScrollView];

    headIV = [[XYScrollView alloc] initPageScrollView:CGRectMake(0, 0, UI_SCREEN_WIDTH, 285) pageControllerFrame:CGRectMake(0, 265, 320, 20) backgroudImage:nil pageNumber:3];
    headIV.delegate = self;
//    headIV.backgroundColor = [UIColor orangeColor];
    headIV.isRunning = YES;
    headIV.userInteractionEnabled = YES;
    [backScrollView addSubview:headIV];

//    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toOthers)];
//    tap.numberOfTapsRequired = 1;
//    [headIV addGestureRecognizer:tap];

//    UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 287, UI_SCREEN_WIDTH, 130)];
//    bgView.backgroundColor = [UIColor whiteColor];
//    bgView.alpha = .7;
//    [self.contentView addSubview:bgView];

    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 285, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT - UI_NAVIGATION_BAR_HEIGHT - 285) style:UITableViewStylePlain];
    myTableView.dataSource = self;
    myTableView.delegate = self;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:myTableView];

//    bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 285, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT - 285 - UI_NAVIGATION_BAR_HEIGHT)];
//    [backScrollView addSubview:bgView];
//
//    UIImageView * IV1 = [[UIImageView alloc] initWithFrame:CGRectMake(29, 17, 379/2.0f, 118/2.0f)];
//    IV1.image = [UIImage imageNamed:@"gametype"];
//    [bgView addSubview:IV1];
//    
//    UIImageView * lineIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 105, 300, .5f)];
//    lineIV.image = [UIImage imageNamed:@"line"];
//    [bgView addSubview:lineIV];
//    
//    UIImageView * IV2 = [[UIImageView alloc] initWithFrame:CGRectMake(33, 131, 361/2.0f, 141/2.0f)];
//    IV2.image = [UIImage imageNamed:@"triptype"];
//    [bgView addSubview:IV2];

    for (int i = 0; i < 2; i++) {
        UIImageView * arrowIV = [[UIImageView alloc] initWithFrame:CGRectMake(291, 40+110*i, 11, 21)];
        arrowIV.image = [UIImage imageNamed:@"arrow_pur"];
        [bgView addSubview:arrowIV];
        
        
        UIButton * btn = [XDTools getAButtonForView:bgView frame:CGRectMake(0, 4+105*i, UI_SCREEN_WIDTH, 100) nomalTitle:nil hlTitle:nil titleColor:nil bgColor:[UIColor clearColor] nbgImage:nil hbgImage:nil action:@selector(typeBtnClick:) target:self buttonTpye:UIButtonTypeCustom];
        btn.tag = 1001+i;
    }

    bgView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 285, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT - 285 - UI_NAVIGATION_BAR_HEIGHT)];
    bgView2.hidden = YES;
    [backScrollView addSubview:bgView2];

    UILabel * titleLB = [[UILabel alloc] initWithFrame:CGRectMake(13, 15, 290, 25)];
    titleLB.text = @"领取奖品";
    [bgView2 addSubview:titleLB];

    for (int i = 0; i < 3; i++) {
        UIButton * btn = [XDTools getAButtonForView:bgView2 frame:CGRectMake(5+(100+5)*i, 55, 100, 40) nomalTitle:nil hlTitle:nil titleColor:nil bgColor:[UIColor clearColor] nbgImage:[NSString stringWithFormat:@"tryPay2_0%d",i+1] hbgImage:nil action:@selector(chooseOne:) target:self buttonTpye:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"tryPay2_0%d",i+4]] forState:UIControlStateSelected];
        btn.tag = 100+i;
        [btnArray addObject:btn];
    }

    [XDTools getAButtonForView:bgView2 frame:CGRectMake(15, 155, 290, 44) nomalTitle:@"确认支付" hlTitle:@"确认支付" titleColor:[UIColor whiteColor] bgColor:RGBA(241, 141, 0, 1) nbgImage:nil hbgImage:nil action:@selector(pay) target:self buttonTpye:UIButtonTypeCustom];
//    [XDTools getAButtonForView:bgView2 frame:CGRectMake(15, 145, 290, 30) nomalTitle:@"校验" hlTitle:@"确认支付" titleColor:[UIColor whiteColor] bgColor:RGBA(118, 75, 217, 1) nbgImage:nil hbgImage:nil action:@selector(xiaoyan) target:self buttonTpye:UIButtonTypeCustom];

    [self getBanner];
    [self getOrderList];
}

- (void)getBanner{
    if ([XDTools NetworkReachable]){

        __weak ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://xindaoapp.com/maodai/plugins/API.v1.0/?&a=category&m=banner"]];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

            if ([tempDic[@"result"] intValue] == 1) {
                NSMutableArray * imaArr = [[NSMutableArray alloc] init];
                for (NSDictionary * dic in tempDic[@"data"]) {
                    [imaArr addObject:dic[@"src"]];
                }

                [headIV setTheImageUrlArray:imaArr andplaceholderImage:nil];
            }else{
                [XDTools showTips:tempDic[@"msg"] toView:self.view];
            }

        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}

- (void)getOrderList{
    if ([XDTools NetworkReachable]){
        
        __weak ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://www.xindaoapp.com/maodai/plugins/API.v1.0/?&a=category&m=activitys"]];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];
            if ([tempDic[@"result"] intValue] == 1) {
                dataArray = [NSMutableArray arrayWithArray:tempDic[@"data"]];
                [myTableView reloadData];
            }else{
                [XDTools showTips:tempDic[@"msg"] toView:self.view];
            }

        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}

- (void)toOthers{
    ThreePriceViewController * three = [[ThreePriceViewController alloc] init];
    [self.navigationController pushViewController:three animated:YES];
}

- (void)chooseOne:(UIButton *)sender{
    for (UIButton * btn in btnArray) {
        btn.selected = NO;
        if (btn == sender) {
            btn.selected = YES;
            NSArray * arr = [NSArray arrayWithObjects:@"100",@"500",@"1500", nil];
            payAmt = arr[sender.tag - 100];
        }

    }

}

- (void)pay{
    if (!(payAmt.intValue > 0)) {
        [XDTools showTips:@"请选择商品" toView:self.view];
        return;
    }

    if (!ISLOGING) {
        LoginViewController * login = [[LoginViewController alloc] init];
        login.payAmt = payAmt;
        [self.navigationController pushViewController:login animated:YES];
    }else{
        [self ruku];
    }

}




- (void)typeBtnClick:(UIButton *)sender{
    TypeListViewController * list = [[TypeListViewController alloc] init];
//    list.type = sender.tag-1000;
    [self.navigationController pushViewController:list animated:YES];
}


- (void)ruku{

    if ([XDTools NetworkReachable]){
        //        NSString *body = [NSString stringWithFormat:@" <ActivityList xmlns=\"http://tempuri.org/\">"
        //                          "</ActivityList>"];
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970]*1000;
        NSString *timeString = [NSString stringWithFormat:@"%f", a];


        NSDictionary * dic = @{@"merId":@"1000002084",
                               @"merOrderNo": timeString,         //商户订单号
                               @"merUserId": @"test",          //商户ID
                               @"notifyUrl": @"http://124.193.184.94",         ////异步回调地址
                               @"opCode": @"33A10H",             //交易码  入库33A10H
                               @"orderDesc": @"0123",          //描述
                               @"orderType":@"",
                               @"payAmt": payAmt,
                               @"productId":@"100006",
                               @"returnUrl":@"http://124.193.184.94",
                               @"userId":@""};

        NSArray * arr = [NSArray arrayWithObjects:@"merId",@"merOrderNo",@"merUserId",@"notifyUrl",@"opCode",@"orderDesc",@"orderType",@"payAmt",@"productId",@"returnUrl",@"userId", nil];


        __weak ASIHTTPRequest * request = [XDTools getRequestWithDict:dic array:arr];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            DDLOG(@"responseString:%@", responseString);

            if ([responseString rangeOfString:@"000000"].length == 6) {
                //保存paytoken
                NSRange range = [responseString rangeOfString:@"orderNo="];
                orderNo = [responseString substringWithRange:NSMakeRange(range.location + range.length, 20)];
                [self jiaoyan];
            }else{
                [XDTools showTips:@"订单入库失败" toView:self.view];
            }


        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}


- (void)jiaoyan{
    if ([XDTools NetworkReachable]){
        //校验
        NSString * userId = [[NSUserDefaults standardUserDefaults] objectForKey:kMMyUserInfo][0];

        NSDictionary * dic = @{@"cpuSerial":@"cpu12323232",
                               @"idNo":@"110108198703126311",                         //身份证
                               @"imei":@"imei32323232",
                               @"imsi":@"imsi123333",
                               @"macAddr":@"mac123",
                               @"merId":@"1000002084",
                               @"merVerifyCodeFlag": @"0",          
                               @"opCode": @"28AC0H",             //交易码  入库33A10H                 1
                               @"orderNo": orderNo,
                               @"userId":userId,
                               @"userIp":@"192.168.1.2"};

        DDLOG(@"dic ::::::  %@",dic);

        NSArray * arr = [NSArray arrayWithObjects:@"cpuSerial",@"idNo",@"imei",@"imsi",@"macAddr",@"merId",@"merVerifyCodeFlag",@"opCode",@"orderNo",@"userId",@"userIp", nil];


        __weak ASIHTTPRequest * request = [XDTools getRequestWithDict:dic array:arr];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];

            DDLOG(@"jiaoyan  responseString:%@", responseString);
            if ([responseString rangeOfString:@"000000"].length == 6) {
                //保存paytoken
                NSRange range = [responseString rangeOfString:@"payToken="];
                payToken = [responseString substringWithRange:NSMakeRange(range.location + range.length, 36)];
                [self zhifu];
            }else{
                [XDTools showTips:@"风险校验失败" toView:self.view];
            }


//            if (!isFirst) {
//                [self secondGetCode];
//            }
//
//            isFirst = NO;
        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
        


    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}

//- (void)secondGetCode{
//    if ([XDTools NetworkReachable]){
//        //再次获取验证码
//        NSDictionary * dic = @{@"merId":@"1000002084",
//                               @"opCode": @"64A007",             //交易码  入库33A10H                 1
//                               @"payToken": payToken};          //校验时获取                                 1
//
//
//        NSArray * arr = [NSArray arrayWithObjects:@"merId",@"opCode",@"payToken", nil];
//
//
//        __weak ASIHTTPRequest * request = [XDTools getRequestWithDict:dic array:arr];
//        [request setCompletionBlock:^{
//            [XDTools hideProgress:self.contentView];
//            NSString *responseString = [request responseString];
//
//            DDLOG(@"responseString:%@", responseString);
//
//            isFirst = NO;
//        }];
//
//        [request setFailedBlock:^{
//            [XDTools hideProgress:self.contentView];
//            NSLog(@"%@",request.error.description);
//        }];
//        [request startAsynchronous];
//        [XDTools showProgress:self.contentView];
//
//    }else{
//        [XDTools showTips:brokenNetwork toView:self.contentView];
//    }
//
//
//}

- (void)zhifu{
    if ([XDTools NetworkReachable]){
        //        NSString *body = [NSString stringWithFormat:@" <ActivityList xmlns=\"http://tempuri.org/\">"
        //                          "</ActivityList>"];

        if (!payToken.length) {
            [XDTools showTips:@"请先获取验证码" toView:self.view];
            return;
        }

        NSString * userId = [[NSUserDefaults standardUserDefaults] objectForKey:kMMyUserInfo][0];


        NSDictionary * dic = @{@"authCode":userId,
                               @"merId":@"1000002084",
                               @"opCode": @"34AC0H",             //交易码  入库33A10H                 1
                               @"payToken": payToken};             //

        NSArray * arr = [NSArray arrayWithObjects:@"authCode",@"merId",@"opCode",@"payToken", nil];


        __weak ASIHTTPRequest * request = [XDTools getRequestWithDict:dic array:arr];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            DDLOG(@"zhifu responseString:%@", responseString);

            if ([responseString rangeOfString:@"000000"].length == 6) {
                [XDTools showTips:@"信用支付成功" toView:self.view];
                [self performSelector:@selector(backPrePage) withObject:nil afterDelay:0.5];
            }else{
                [XDTools showTips:@"信用支付失败" toView:self.view];
            }

        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.contentView];
            NSLog(@"%@",request.error.description);
        }];
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}



#pragma mark - TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * cellIde = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];
        cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;
        UIImageView * lineIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 109.5f, 320, .5f)];
        lineIV.image = [UIImage imageNamed:@"line"];
        [cell.contentView addSubview:lineIV];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIImageView * headerIV = [[UIImageView alloc] initWithFrame:CGRectMake(20, 15, 361/2.0f, 70)];
        headerIV.tag = 720;
        [cell.contentView addSubview:headerIV];

//        UILabel * label = [XDTools addAlabelForAView:cell.contentView withText:nil frame:CGRectMake(100, 35, 160, 40) font:[UIFont systemFontOfSize:17] textColor:RGBA(68, 68, 68, 1)];
//        label.tag = 721;

    }

    UIImageView * imageview = (UIImageView *)[cell.contentView viewWithTag:720];
//    UILabel * label = (UILabel *)[cell.contentView viewWithTag:721];
    [imageview setImageWithURL:[NSURL URLWithString:dataArray[indexPath.row][@"keywords"]] placeholderImage:nil];
//    label.text = dataArray[indexPath.row][@"cat_name"];

    return cell;
}

#pragma mark - TableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    跳转APP
//    NSString *str = @"nav://com.b.nav?viewId=%@";
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:str, @"nav"]];
//    [[UIApplication sharedApplication] openURL:url];
    TypeListViewController * list = [[TypeListViewController alloc] init];
    list.suppliers_id = dataArray[indexPath.row][@"cat_id"];
    list.titleName = dataArray[indexPath.row][@"cat_name"];
    [self.navigationController pushViewController:list animated:YES];
}

//- (void)viewDidDisappear:(BOOL)animated{
//    [headIV closeTimerTask];
//    [self viewDidDisappear:YES];
//}

-(void)gestureClick:(UITapGestureRecognizer *)sender{
    switch (sender.view.tag - 10000) {
        case 1:
        {
            GoodsDetailViewController * detail = [[GoodsDetailViewController alloc] init];
            detail.goodsID = @"1";
            [self.navigationController pushViewController:detail animated:YES];
        }
            break;
        case 2:
        {
            GoodsDetailViewController * detail = [[GoodsDetailViewController alloc] init];
            detail.goodsID = @"3";
            [self.navigationController pushViewController:detail animated:YES];
        }
            break;
        case 3:
            if (!ISLOGING) {
                [self toOthers];
            }
            break;
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
